package com.delayqueue.registry.netty.handler;

import com.alibaba.fastjson.JSON;
import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.Address;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.common.netty.NettyUtil;
import com.delayqueue.common.netty.Node;
import com.delayqueue.registry.netty.cache.NodeCacheFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

public class MessageInBoundHandler extends SimpleChannelInboundHandler<NettyMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, NettyMessage message) throws Exception {
        MessageType messageType = message.getMessageType();
        if (messageType == MessageType.CORE_ONLINE) {
            Address remoteAddress = NettyUtil.getRemoteAddress(channelHandlerContext);

            NodeCacheFactory.core.add(remoteAddress.getIp(), remoteAddress.getPort(), channelHandlerContext);

            List<String> addresList = NodeCacheFactory.master.getAllConnectAddress();
            if (!addresList.isEmpty()) {
                NettyMessage nettyMessage = new NettyMessage(MessageType.MASTER_ALL, JSON.toJSONString(addresList));
                channelHandlerContext.writeAndFlush(nettyMessage);
            }

        } else if (messageType == MessageType.MASTER_ONLINE) {
            Address remoteAddress = NettyUtil.getRemoteAddress(channelHandlerContext);
            String port = message.getMessageContent();

            Node node = new Node(remoteAddress.getIp(), remoteAddress.getPort());
            node.setConnectPort(Integer.parseInt(port));
            node.setChannelHandlerContext(channelHandlerContext);
            NodeCacheFactory.master.add(node);

            NettyMessage nettyMessage = new NettyMessage(MessageType.MASTER_ONLINE, remoteAddress.getIp() + ":" + port);
            NodeCacheFactory.core.broadCastMessage(nettyMessage);
        }
    }
}
